<?php

namespace App\Jobs\user;

use App\Models\config\Config;
use App\Models\fund\Coupon;
use App\Models\log\ErrorLog;
use App\Models\User;
use App\Models\user\UserSuperior;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Http\Request;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\DB;

class BuildUserSuperior implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 任务最大尝试次数。
     *
     * @var int
     */
    public $tries = 5;

    protected $user;

    /**
     *
     *
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct( $user)
    {
        $this->user = $user;
    }

    /**
     * 用户创建事件   用户关系建立事件
     *
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try{

            if ($this->user->superior_id && $this->user->superior){

                $rows  = [];

                $array = UserSuperior::orderBy('level')->where('user_id',$this->user->superior_id)->get();

                if ($array->isNotEmpty()){
                    foreach ($array as $value){
                        $row['user_id'] = $this->user->id;
                        $row['superior_id'] = $value->superior_id;
                        $row['level'] = $value->level + 1;
                        $row['user_level'] = $value->user_level;
                        $row['rebate'] = 0;
                        $row['created_at'] = Carbon::now();
                        $row['updated_at'] = Carbon::now();
                        $rows[]  = $row;
                    }
                }
                $row = [];
                $row['user_id'] = $this->user->id;
                $row['superior_id'] = $this->user->superior_id;
                $row['level'] = 1;
                $row['user_level'] = $this->user->superior->level;
                $row['rebate'] = 0;
                $row['created_at'] = Carbon::now();
                $row['updated_at'] = Carbon::now();

                array_push($rows,$row);

                DB::table('user_superiors')->insert($rows);

            }

        }catch (\Exception $e){
            dump($e->getMessage());
            $log['msg']     = $e->getMessage();
            $log['params']  = $this->user;
            $log['content'] = $e;
            ErrorLog::create($log);
        }
    }

    public function failed(\Exception $exception)
    {

    }

}
